﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace SharpKeeperLib
{
    public class KObject
    {
        public readonly String UniqueID = Guid.NewGuid().ToString();
        protected int Locks = 0;
        public KObjectList Children = new KObjectList();
        public KObject Parent = null;

        public KObject()
        {

        }

        public KObject(KObject parent)
        {
            Parent = parent;
        }

        public void SetParent(KObject parent)
        {
            Lock();

            if (Parent != null)
            {
                Parent.Lock();
                if (parent.Children.Contains(this))
                    Parent.Children.Remove(this);
                Parent.Unlock();
            }

            parent.Lock();

            if (!parent.Children.Contains(this))
            {
                parent.Children.Add(this);
                Parent = parent;
            }

            parent.Unlock();
            Unlock();
        }

        public void Lock()
        {
            lock (this)
            {
                Locks++;
                Monitor.Enter(this);
            }
        }

        public void Unlock()
        {
            lock (this)
            {
                if (Locks > 0)
                {
                    Locks--;
                    Monitor.Exit(this);
                }
            }
        }

        public void UnlockAll()
        {
            lock (this)
            {
                for (int i =0;i < Locks; i++)
                {
                    Unlock();
                }
            }
        }
    }
}
